<template>
  <div class="template-creator-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>创建简历模板</h2>
        <p>自定义您的简历模板样式</p>
      </div>
      <div class="header-actions">
        <el-button @click="handlePreview" type="primary">预览</el-button>
        <el-button @click="handleSave" type="success">保存模板</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </div>

    <el-row :gutter="24" class="creator-content">
      <!-- 左侧：样式编辑器 -->
      <el-col :span="10" class="editor-column">
        <el-card class="editor-card">
          <el-tabs v-model="activeTab">
            <!-- 基本设置 -->
            <el-tab-pane label="基本设置" name="basic">
              <el-form label-width="100px">
                <el-form-item label="模板名称">
                  <el-input v-model="templateData.name" placeholder="请输入模板名称" />
                </el-form-item>

                <el-form-item label="布局类型">
                  <el-select v-model="templateData.layout" placeholder="请选择">
                    <el-option label="左右布局" value="left-right" />
                    <el-option label="上下布局" value="top-bottom" />
                    <el-option label="侧边栏布局" value="sidebar" />
                  </el-select>
                </el-form-item>

                <el-form-item label="主题色">
                  <el-color-picker v-model="templateData.style.base.primaryColor" show-alpha />
                </el-form-item>

                <el-form-item label="次要颜色">
                  <el-color-picker v-model="templateData.style.base.secondaryColor" show-alpha />
                </el-form-item>

                <el-form-item label="背景色">
                  <el-color-picker v-model="templateData.style.base.bgColor" show-alpha />
                </el-form-item>

                <el-form-item label="字体">
                  <el-select v-model="templateData.style.base.fontFamily">
                    <el-option label="微软雅黑" value="Microsoft YaHei, sans-serif" />
                    <el-option label="宋体" value="SimSun, serif" />
                    <el-option label="黑体" value="SimHei, sans-serif" />
                    <el-option label="苹方" value="PingFang SC, sans-serif" />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 姓名设置 -->
            <el-tab-pane label="姓名" name="name">
              <el-form label-width="100px">
                <el-form-item label="字体大小">
                  <el-slider v-model="templateData.style.basic.name.fontSize" :min="18" :max="36" />
                  <span class="value-display">{{ templateData.style.basic.name.fontSize }}px</span>
                </el-form-item>

                <el-form-item label="字体粗细">
                  <el-radio-group v-model="templateData.style.basic.name.fontWeight">
                    <el-radio label="normal">正常</el-radio>
                    <el-radio label="bold">粗体</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="对齐方式">
                  <el-radio-group v-model="templateData.style.basic.name.textAlign">
                    <el-radio label="left">左对齐</el-radio>
                    <el-radio label="center">居中</el-radio>
                    <el-radio label="right">右对齐</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="字间距">
                  <el-slider v-model="nameLetterSpacing" :min="0" :max="10" />
                  <span class="value-display">{{ nameLetterSpacing }}px</span>
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 标题设置 -->
            <el-tab-pane label="标题" name="title">
              <el-form label-width="100px">
                <el-form-item label="字体大小">
                  <el-slider v-model="sharedTitleFontSize" :min="14" :max="24" />
                  <span class="value-display">{{ sharedTitleFontSize }}px</span>
                </el-form-item>

                <el-form-item label="颜色">
                  <el-color-picker v-model="sharedTitleColor" show-alpha />
                </el-form-item>

                <el-form-item label="底部边框">
                  <el-switch v-model="showTitleBorder" />
                </el-form-item>

                <el-form-item label="边框颜色" v-if="showTitleBorder">
                  <el-color-picker v-model="titleBorderColor" show-alpha />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 内容设置 -->
            <el-tab-pane label="内容" name="content">
              <el-form label-width="100px">
                <el-form-item label="字体大小">
                  <el-slider v-model="contentFontSize" :min="12" :max="18" />
                  <span class="value-display">{{ contentFontSize }}px</span>
                </el-form-item>

                <el-form-item label="行高">
                  <el-slider v-model="contentLineHeight" :min="1.2" :max="2.0" :step="0.1" />
                  <span class="value-display">{{ contentLineHeight }}</span>
                </el-form-item>

                <el-form-item label="圆角">
                  <el-slider v-model="itemBorderRadius" :min="0" :max="20" />
                  <span class="value-display">{{ itemBorderRadius }}px</span>
                </el-form-item>

                <el-form-item label="阴影">
                  <el-switch v-model="showItemShadow" />
                </el-form-item>
              </el-form>
            </el-tab-pane>

            <!-- 照片设置 -->
            <el-tab-pane label="照片" name="photo">
              <el-form label-width="100px">
                <el-form-item label="显示照片">
                  <el-switch v-model="showPhoto" />
                </el-form-item>

                <el-form-item label="宽度" v-if="showPhoto">
                  <el-slider v-model="templateData.style.photo.width" :min="80" :max="150" />
                  <span class="value-display">{{ templateData.style.photo.width }}px</span>
                </el-form-item>

                <el-form-item label="高度" v-if="showPhoto">
                  <el-slider v-model="templateData.style.photo.height" :min="80" :max="150" />
                  <span class="value-display">{{ templateData.style.photo.height }}px</span>
                </el-form-item>

                <el-form-item label="圆角" v-if="showPhoto">
                  <el-slider v-model="templateData.style.photo.borderRadius" :min="0" :max="75" />
                  <span class="value-display">{{ templateData.style.photo.borderRadius }}px</span>
                </el-form-item>

                <el-form-item label="边框宽度" v-if="showPhoto">
                  <el-slider v-model="photoBorderWidth" :min="0" :max="10" />
                  <span class="value-display">{{ photoBorderWidth }}px</span>
                </el-form-item>

                <el-form-item label="边框颜色" v-if="showPhoto">
                  <el-color-picker v-model="photoBorderColor" show-alpha />
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>

      <!-- 右侧：实时预览 -->
      <el-col :span="14" class="preview-column">
        <el-card class="preview-card">
          <div class="preview-title">实时预览</div>
          <div class="preview-content" :style="previewStyle">
            <!-- 基本信息 -->
            <div class="preview-section" style="display: flex; justify-content: space-between; align-items: flex-start;">
              <div style="flex: 1;">
                <h2 class="preview-name" :style="nameStyle">张三</h2>
                <div class="preview-info" :style="infoStyle">
                  <p>电话: 13800138000</p>
                  <p>邮箱: zhangsan@example.com</p>
                  <p>意向: 前端开发工程师</p>
                </div>
                <p class="preview-intro" :style="introStyle">
                  5年前端开发经验，精通Vue、React等主流框架，具有良好的团队协作能力和代码规范意识。
                </p>
              </div>
              <!-- 照片预览 -->
              <div v-if="showPhoto" :style="{
                width: templateData.style.photo.width + 'px',
                height: templateData.style.photo.height + 'px',
                border: templateData.style.photo.border,
                borderRadius: templateData.style.photo.borderRadius + 'px',
                overflow: 'hidden',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                backgroundColor: '#f0f0f0',
                color: '#999',
                fontSize: '12px',
                flexShrink: 0,
                marginLeft: '20px'
              }">
                照片
              </div>
            </div>

            <!-- 教育经历 -->
            <div class="preview-section">
              <h3 class="section-title" :style="titleStyle">教育经历</h3>
              <div class="preview-item" :style="itemStyle">
                <div class="item-header">
                  <span class="item-main" :style="itemMainStyle">XX大学 - 计算机科学与技术</span>
                  <span class="item-date" :style="itemDateStyle">2015.09 - 2019.06</span>
                </div>
              </div>
            </div>

            <!-- 工作经验 -->
            <div class="preview-section">
              <h3 class="section-title" :style="titleStyle">工作经验</h3>
              <div class="preview-item" :style="itemStyle">
                <div class="item-header">
                  <span class="item-main" :style="itemMainStyle">XX科技有限公司 - 前端开发工程师</span>
                  <span class="item-date" :style="itemDateStyle">2019.07 - 至今</span>
                </div>
                <p class="item-desc" :style="itemDescStyle">
                  负责公司核心产品的前端开发工作，使用Vue3进行项目重构，性能提升30%。
                </p>
              </div>
            </div>

            <!-- 技能特长 -->
            <div class="preview-section">
              <h3 class="section-title" :style="titleStyle">技能特长</h3>
              <p :style="skillsTextStyle">
                Vue3、React、TypeScript、Node.js、Webpack、Git
              </p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const activeTab = ref('basic');

// 模板数据
const templateData = ref({
  name: '我的模板',
  layout: 'left-right',
  modules: ['photo', 'basic', 'education', 'work', 'skills'],
  style: {
    base: {
      fontFamily: 'Microsoft YaHei, sans-serif',
      primaryColor: '#2c3e50',
      secondaryColor: '#7f8c8d',
      bgColor: '#ffffff',
      spacing: 14,
      dividerColor: '#ecf0f1',
      padding: '20px',
      maxWidth: '750px',
      margin: '0 auto',
      borderRadius: '0px'
    },
    photo: {
      width: 100,
      height: 100,
      border: '2px solid #ecf0f1',
      borderRadius: 8
    },
    basic: {
      name: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'left',
        margin: '0 0 10px 0',
        letterSpacing: 'normal'
      }
    }
  }
});

// 辅助变量（用于双向绑定）
const nameLetterSpacing = ref(0);
const sharedTitleFontSize = ref(16);
const sharedTitleColor = ref('#2c3e50');
const showTitleBorder = ref(true);
const titleBorderColor = ref('#ecf0f1');
const contentFontSize = ref(14);
const contentLineHeight = ref(1.6);
const itemBorderRadius = ref(8);
const showItemShadow = ref(true);
const showPhoto = ref(true);
const photoBorderWidth = ref(2);
const photoBorderColor = ref('#ecf0f1');

// 监听基本设置的变化（颜色、字体等）
watch(() => templateData.value.style.base, (newVal) => {
  console.log('基本设置变化:', newVal);
  // 当基本设置变化时，更新相关的次要颜色引用
  if (templateData.value.style.education?.itemDate) {
    templateData.value.style.education.itemDate.color = templateData.value.style.base.secondaryColor;
  }
  if (templateData.value.style.work?.itemDate) {
    templateData.value.style.work.itemDate.color = templateData.value.style.base.secondaryColor;
  }
  if (templateData.value.style.work?.itemDesc) {
    templateData.value.style.work.itemDesc.color = templateData.value.style.base.secondaryColor;
  }
  if (templateData.value.style.skills?.content) {
    templateData.value.style.skills.content.color = templateData.value.style.base.secondaryColor;
  }
}, { deep: true });

// 监听辅助变量变化，同步到templateData
watch(nameLetterSpacing, (val) => {
  templateData.value.style.basic.name.letterSpacing = val + 'px';
}, { immediate: true });

watch([sharedTitleFontSize, sharedTitleColor, showTitleBorder, titleBorderColor], () => {
  const borderBottom = showTitleBorder.value ? `2px solid ${titleBorderColor.value}` : 'none';
  
  // 同步到所有标题
  if (!templateData.value.style.education) templateData.value.style.education = {};
  if (!templateData.value.style.work) templateData.value.style.work = {};
  if (!templateData.value.style.skills) templateData.value.style.skills = {};
  
  templateData.value.style.education.title = {
    fontSize: sharedTitleFontSize.value,
    fontWeight: 600,
    color: sharedTitleColor.value,
    margin: '0 0 12px 0',
    paddingBottom: 4,
    borderBottom: borderBottom
  };
  
  templateData.value.style.work.title = { ...templateData.value.style.education.title };
  templateData.value.style.skills.title = { ...templateData.value.style.education.title };
}, { immediate: true });

watch([contentFontSize, contentLineHeight, itemBorderRadius, showItemShadow], () => {
  const boxShadow = showItemShadow.value ? '0 2px 6px rgba(0,0,0,0.05)' : 'none';
  
  if (!templateData.value.style.education) templateData.value.style.education = {};
  if (!templateData.value.style.work) templateData.value.style.work = {};
  
  // 教育经历
  templateData.value.style.education.item = {
    marginBottom: 14,
    padding: '12px 15px',
    backgroundColor: '#ffffff',
    borderRadius: itemBorderRadius.value,
    boxShadow: boxShadow
  };
  
  templateData.value.style.education.itemHeader = {
    fontSize: contentFontSize.value,
    justifyContent: 'space-between'
  };
  
  templateData.value.style.education.itemDate = {
    fontSize: contentFontSize.value - 1,
    color: templateData.value.style.base.secondaryColor
  };
  
  templateData.value.style.education.itemMain = {
    fontWeight: 500,
    color: templateData.value.style.base.primaryColor
  };
  
  // 工作经验
  templateData.value.style.work.item = { ...templateData.value.style.education.item };
  templateData.value.style.work.itemHeader = { ...templateData.value.style.education.itemHeader };
  templateData.value.style.work.itemDate = { ...templateData.value.style.education.itemDate };
  templateData.value.style.work.itemMain = { ...templateData.value.style.education.itemMain };
  
  templateData.value.style.work.itemDesc = {
    fontSize: contentFontSize.value - 1,
    lineHeight: contentLineHeight.value,
    marginTop: 6,
    color: templateData.value.style.base.secondaryColor
  };
  
  // 技能特长
  if (!templateData.value.style.skills) templateData.value.style.skills = {};
  templateData.value.style.skills.content = {
    fontSize: contentFontSize.value,
    lineHeight: contentLineHeight.value,
    color: templateData.value.style.base.secondaryColor
  };
}, { immediate: true });

watch([showPhoto, photoBorderWidth, photoBorderColor], () => {
  if (showPhoto.value) {
    templateData.value.modules = ['photo', 'basic', 'education', 'work', 'skills'];
    templateData.value.style.photo.border = `${photoBorderWidth.value}px solid ${photoBorderColor.value}`;
  } else {
    templateData.value.modules = ['basic', 'education', 'work', 'skills'];
  }
}, { immediate: true });

// 预览样式
const previewStyle = computed(() => ({
  fontFamily: templateData.value.style.base.fontFamily,
  color: templateData.value.style.base.primaryColor,
  backgroundColor: templateData.value.style.base.bgColor,
  padding: '20px',
  borderRadius: templateData.value.style.base.borderRadius,
  minHeight: '600px'
}));

const nameStyle = computed(() => ({
  fontSize: templateData.value.style.basic.name.fontSize + 'px',
  fontWeight: templateData.value.style.basic.name.fontWeight,
  textAlign: templateData.value.style.basic.name.textAlign,
  margin: templateData.value.style.basic.name.margin,
  letterSpacing: templateData.value.style.basic.name.letterSpacing,
  color: templateData.value.style.base.primaryColor
}));

const infoStyle = computed(() => ({
  fontSize: contentFontSize.value + 'px',
  color: templateData.value.style.base.secondaryColor,
  marginBottom: '10px'
}));

const introStyle = computed(() => ({
  fontSize: contentFontSize.value + 'px',
  lineHeight: contentLineHeight.value,
  color: templateData.value.style.base.secondaryColor
}));

const titleStyle = computed(() => ({
  fontSize: sharedTitleFontSize.value + 'px',
  fontWeight: 600,
  color: sharedTitleColor.value,
  margin: '20px 0 12px 0',
  paddingBottom: '4px',
  borderBottom: showTitleBorder.value ? `2px solid ${titleBorderColor.value}` : 'none'
}));

const itemStyle = computed(() => ({
  marginBottom: '14px',
  padding: '12px 15px',
  backgroundColor: '#ffffff',
  borderRadius: itemBorderRadius.value + 'px',
  boxShadow: showItemShadow.value ? '0 2px 6px rgba(0,0,0,0.05)' : 'none'
}));

const itemMainStyle = computed(() => ({
  fontWeight: 500,
  color: templateData.value.style.base.primaryColor,
  fontSize: contentFontSize.value + 'px'
}));

const itemDateStyle = computed(() => ({
  fontSize: (contentFontSize.value - 1) + 'px',
  color: templateData.value.style.base.secondaryColor
}));

const itemDescStyle = computed(() => ({
  fontSize: (contentFontSize.value - 1) + 'px',
  lineHeight: contentLineHeight.value,
  marginTop: '6px',
  color: templateData.value.style.base.secondaryColor
}));

const skillsTextStyle = computed(() => ({
  fontSize: contentFontSize.value + 'px',
  lineHeight: contentLineHeight.value,
  color: templateData.value.style.base.secondaryColor
}));

// 预览
const handlePreview = () => {
  ElMessage.info('预览功能开发中...');
};

// 保存模板
const handleSave = async () => {
  if (!templateData.value.name.trim()) {
    ElMessage.error('请输入模板名称');
    return;
  }

  try {
    // 从store获取当前登录用户ID
    const store = useStore()
    const currentUserId = store.app.userId
    if (!currentUserId) {
      ElMessage.error('请先登录')
      return
    }
    
    const postData = {
      name: templateData.value.name,
      template_data: templateData.value,
      user_id: parseInt(currentUserId) // 从store获取当前登录用户ID
    };
    
    console.log('准备保存的模板数据:', postData);
    
    const response = await axios.post('http://localhost:7001/api/templates', postData);

    console.log('服务器响应:', response.data);

    if (response.data.code === 0) {
      ElMessage.success('模板保存成功');
      router.push('/editor');
    } else {
      ElMessage.error(response.data.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存模板失败:', error);
    console.error('错误详情:', error.response?.data);
    ElMessage.error(error.response?.data?.msg || '保存失败，请重试');
  }
};

// 取消
const handleCancel = () => {
  router.back();
};
</script>

<style scoped>
.template-creator-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.creator-content {
  max-width: 1400px;
  margin: 0 auto;
}

.editor-card,
.preview-card {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  min-height: 700px;
}

.editor-column {
  max-height: calc(100vh - 180px);
  overflow-y: auto;
}

.value-display {
  margin-left: 12px;
  color: #666;
  font-size: 14px;
}

.preview-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.preview-content {
  border-radius: 8px;
}

.preview-section {
  margin-bottom: 20px;
}

.preview-name {
  margin: 0 0 10px 0;
}

.preview-info p {
  margin: 4px 0;
}

.preview-intro {
  margin: 10px 0;
}

.section-title {
  margin: 20px 0 12px 0;
}

.preview-item {
  margin-bottom: 14px;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-desc {
  margin: 6px 0 0 0;
}

/* 滚动条样式 */
.editor-column::-webkit-scrollbar {
  width: 6px;
}

.editor-column::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.editor-column::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.editor-column::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>

